package cnam.smb215.findfriends;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class RegistrationActivity extends Activity {
	final int REQ_CODE_GALLERY = 1;
	EditText editTextName, editTextEmail;
	Button buttonSignup;
	ImageView imageViewPicture;
	Bitmap scaledSelectedImage;
	ProgressBar progressBarSingUp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);

		//Globals initialization
		if(Globals.DEFAULT_ICON == null) {
			Globals.DEFAULT_ICON = this.getResources().getDrawable(R.drawable.pin_green);
		}
		if(Globals.DEFAULT_ICON_USERS == null) {
			Globals.DEFAULT_ICON_USERS = this.getResources().getDrawable(R.drawable.pin_red);
		}

		editTextName = (EditText)findViewById(R.id.editTextName);
		editTextEmail = (EditText)findViewById(R.id.editTextEmail);
		buttonSignup = (Button)findViewById(R.id.buttonSignUp);
		imageViewPicture = (ImageView)findViewById(R.id.imageViewPicture);
		progressBarSingUp = (ProgressBar)findViewById(R.id.progressBarSignUp);
		imageViewPicture.setImageDrawable(Globals.DEFAULT_ICON);

		imageViewPicture.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				RegistrationActivity.this.startActivityForResult(intent, REQ_CODE_GALLERY); 
			}
		});

		buttonSignup.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				if(editTextName.getText() == null || editTextName.getText().toString().length() == 0) {
					toastMessage("Name is empty!");
					return;
				}
				if(editTextEmail.getText() == null || editTextEmail.getText().toString().length() == 0) {
					toastMessage("Email is empty!");
					return;
				}
				if(editTextEmail.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+") == false) {
					toastMessage("Email format is wrong!");
					return;
				}

				//views changes
				progressBarSingUp.setVisibility(View.VISIBLE);
				buttonSignup.setEnabled(false);
				editTextName.setEnabled(false);
				editTextEmail.setEnabled(false);
				
				String name = editTextName.getText().toString();
				String email = editTextEmail.getText().toString();
				
				SignUpTask signUpTask = new SignUpTask();
				signUpTask.execute(email, name);
			}
		});
	}

//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
//		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
//
//		switch (requestCode) {
//		case REQ_CODE_GALLERY:
//			if(resultCode == RESULT_OK){
//				Uri selectedImage = imageReturnedIntent.getData();
//				String[] filePathColumn = {MediaStore.Images.Media.DATA};
//
//				Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//				cursor.moveToFirst();
//
//				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//				String filePath = cursor.getString(columnIndex);
//				cursor.close();
//
//
//				Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
//				scaledSelectedImage = Bitmap.createScaledBitmap(yourSelectedImage, Globals.USER_IMAGE_WIDTH, Globals.USER_IMAGE_HEIGHT, true);
//				yourSelectedImage.recycle();
//
//				imageViewPicture.setImageBitmap(scaledSelectedImage);
//			}
//			break;
//		}
//	}

	@Override
	protected void onResume() {
		super.onResume();
		if(Globals.FORCE_CLOSE_REGISTRATION) {
			finish();
		}
	}

	private void toastMessage(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}
	
	private void enableViews() {
		//views changes
		progressBarSingUp.setVisibility(View.INVISIBLE);
		buttonSignup.setEnabled(true);
		editTextName.setEnabled(true);
		editTextEmail.setEnabled(true);
	}
	
	private void saveUserInfo(int userID) {
		String name = editTextName.getText().toString();
		String email = editTextEmail.getText().toString();
		
		SharedPreferences sharedPreferences = getSharedPreferences(Globals.FILE_NAME_PREF, 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();

		editor.putBoolean(Globals.PREF_FIRST_RUN, false);
		editor.putInt(Globals.PREF_ID, userID);
		editor.putString(Globals.PREF_NAME, name);
		editor.putString(Globals.PREF_EMAIL, email);

		editor.commit();

		Globals.FORCE_CLOSE_REGISTRATION = true;
		
		toastMessage("Registration Successful!");
		Intent myIntent = new Intent(RegistrationActivity.this, MainActivity.class);
		RegistrationActivity.this.startActivity(myIntent);
	}

	private class SignUpTask extends AsyncTask<String, Void, Integer> {
		@Override
		protected Integer doInBackground(String... params) {
			String response = "";
			String url = Globals.SERVER_URL;
			//url += "?" + Globals.URL_PARAM_TYPE + "=" + Globals.TYPE_SIGN_UP;
			//url += "&" + Globals.URL_PARAM_EMAIL + "=" + params[0];
			//url += "&" + Globals.URL_PARAM_NAME + "=" + params[1];
						
			//url += URLEncodedUtils.format(getParams, "utf-8");

			DefaultHttpClient client = new DefaultHttpClient();			
			HttpPost httpPost = new HttpPost(url);

			try {
				List<NameValuePair> getParams = new LinkedList<NameValuePair>();
				getParams.add(new BasicNameValuePair(Globals.URL_PARAM_TYPE, String.valueOf(Globals.TYPE_SIGN_UP)));
				getParams.add(new BasicNameValuePair(Globals.URL_PARAM_EMAIL, params[0]));
				getParams.add(new BasicNameValuePair(Globals.URL_PARAM_NAME, params[1]));
				httpPost.setEntity(new UrlEncodedFormEntity(getParams));

				HttpResponse execute = client.execute(httpPost);
				InputStream content = execute.getEntity().getContent();

				BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
				String s = "";
				while ((s = buffer.readLine()) != null) {
					response += s;
				}
				
				int res_id = Integer.parseInt(response);
				return res_id;

			} catch (Exception e) {
				Log.e("findFriends", "Error with server: " + e.getMessage());
				return null;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if(result == null) {
				toastMessage("Error with Server!! Please try again after checking your connection");
				enableViews();
			}
			else if(result == -1) {
				toastMessage("Email is already taken, please enter another email");
				enableViews();
			}
			else {
				saveUserInfo(result);
			}
		}

	}
}
